'''
Created on Jan 17, 2010

@author: roman

$Id: links.py 17 2010-01-19 16:57:16Z sigizmund $
'''

import re
import os
import logging 
import pprint
from google.appengine.ext.webapp import template

from django.core.paginator import ObjectPaginator, InvalidPage

from model.twitterstatus import TwitterStatus



class LinksUI:
    def __init__(self, username, filter = None, request = None):
        self.username = username
        self.filter = filter
        self.request = request
    
    def render(self, out):
        
        try:
            page = int(self.request.get('page'))
        except ValueError:
            page = 0
        
        if self.filter != None:
            try:
                q = TwitterStatus.all().search(self.filter)
            except:
                q = TwitterStatus.all().search('nevertobefoundever')
        else:
            q = TwitterStatus.all()
        
        q.filter("urls != ", '')
        q.filter("user = ", self.username.lower())

        q.order("urls")
        q.order("-createdAt")
        
        statuses = sorted(q.fetch(1000), key = lambda x : x.createdAt)
        statuses.reverse()
        
        if self.filter == None:
            self.filter = ''
        
        
        logging.debug(statuses)
        
        paginator = ObjectPaginator(statuses, 10)
        logging.debug("Created paginator: " + pprint.pformat(paginator))  
        logging.debug("paginator.hits = %d, paginator.pages = %d" % (paginator.hits, paginator.pages))

        try:
            stats = paginator.get_page(page)          
        except (InvalidPage):           
            page = 0
            stats = paginator.get_page(page)        
            
        template_values = {
            'username': self.username,
#            'statuses' : statuses,
            'stats_pages' : stats,
            'search' : self.filter,
            'paginator' : paginator,
            'current_page' : page + 1,   
            'total_pages' : paginator.pages,
            'has_previous' : paginator.has_previous_page(page),
            'previous_page' : page-1,
            'has_next' : paginator.has_next_page(page),
            'next_page' : page+1,
            'len_stats' : len(statuses) > 0
         }

        logging.debug(pprint.pformat(template_values))
        
        path = os.path.join('templates/mytwilinks.html')
        out.write(template.render(path, template_values))
    